package com.freely.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.freely.FR;
import com.freely.R;
import com.freely.R2;
import com.freely.component.activity.NavigationActivity;
import com.freely.data.network.ServerException;
import com.freely.data.network.requestEntities.RQDeviceCode;
import com.freely.data.network.requestEntities.RQUserLogin;
import com.freely.data.network.requestEntities.RQVerificationCheck;
import com.freely.data.services.FreelyService;
import com.freely.ui.util.DataVerification;
import com.freely.ui.util.ErrorUtil;
import com.freely.ui.util.VerificationUtil;
import com.freely.ui.viewModel.LoginViewModel;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import androidx.appcompat.widget.AppCompatButton;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class LoginActivity extends NavigationActivity {
    private static final String TAG = "LoginActivity";

    @BindView(R2.id.user_head_icon)
    ImageView headIcon;//登陆页面头像
    @BindView(R2.id.user_account_layout)
    TextInputLayout userAccountLayout;//账号布局
    @BindView(R2.id.user_account)
    TextInputEditText userAccount;//账号
    @BindView(R2.id.user_password_layout)
    TextInputLayout userPasswordLayout;//密码布局
    @BindView(R2.id.user_password)
    TextInputEditText userPassword;//密码
    @BindView(R2.id.login_button)
    AppCompatButton login;//登陆按钮
    @BindView(R2.id.register_button)
    TextView register;//注册按钮
    @BindView(R2.id.reset_password_button)
    TextView resetPassword;//找回密码按钮
    @BindView(R2.id.input_verification_code_layout)
    TextInputLayout verificationCodeLayout;//验证码布局
    @BindView(R2.id.input_verification_code)
    TextInputEditText verificationCode;//验证码
    @BindView(R2.id.verification_code_image)
    ImageView verificationCodeImage;//验证码图像
    private LoginViewModel viewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        viewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        viewInit();
    }

    //注册按钮监听
    @OnClick(R2.id.register_button)
    void registerOnClick() {
        RegisterActivity.startActivity(this);
    }

    //找回密码
    @OnClick(R2.id.reset_password_button)
    void resetPassword(){
        ForgetPasswordActivity.Companion.startActivity(this);
    }

  //登陆按钮监听
    @OnClick(R2.id.login_button)
    void loginOnClick(){
        if (loginVerification()) {
            RQVerificationCheck verificationCheck = new RQVerificationCheck(FR.deviceCodeContent, verificationCode
                    .getText().toString());
            viewModel.checkVerificationCode(verificationCheck);
        }
    }

    //用户账号验证
    @OnTextChanged(R2.id.user_account)
    void userAccountTextChangedListener(Editable s){
        VerificationUtil.accountVerificationHint(
                s.toString(),
                userAccountLayout,
                getString(R.string.user_account_format_error_hint),
                getString(R.string.user_account_length_error_hint)
        );
    }

    //用户密码验证
    @OnTextChanged(R2.id.user_password)
    void userPasswordTextChangedListener(Editable s) {
        VerificationUtil.passwordVerificationHint(
                s.toString(),
                userPasswordLayout,
                getString(R.string.user_password_format_error_hint),
                getString(R.string.user_password_length_error_hint)
        );
    }

    //toolbar 返回图标
    @Override
    protected int navigationIcon() {
        return R.drawable.ic_close;
    }

    //toolbar 标题
    @Override
    protected CharSequence navigationTitle() {
        return getResources().getString(R.string.login);
    }

    //activity 初始化
    private void viewInit() {
        //得到验证码回调
        //错误流程
        viewModel.getVerificationCodeImage().observe(this, single -> single.subscribe(bytes -> {
            //显示验证码
            Glide.with(LoginActivity.this)
                    .asBitmap()
                    .load(bytes)
                    .into(verificationCodeImage);
        }, ErrorUtil::errorHint).dispose());

        //验证验证码结果回调
        viewModel.getVerificationCodeCheckResult().observe(this, single -> single.subscribe(result -> {
            Log.d(TAG, "loginOnClick: 开始登陆");
            //验证码正确，开始登陆
            RQUserLogin userLogin = new RQUserLogin(
                    FR.deviceCodeContent,
                    userAccount.getText().toString(),
                    userPassword.getText().toString()
            );
            viewModel.userLogin(userLogin);
        }, ErrorUtil::errorHint).dispose());

        //登陆成功回调
        viewModel.getLogin().observe(this, userSingle -> userSingle.subscribe(user -> {
            //登陆成功
            Intent intent = new Intent(this, FreelyService.class);
            Log.d(TAG, "onCreate: 开启服务");
            startService(intent);
            Log.d(TAG, "onCreate: 开启完毕");
            HomeActivity.startActivity(LoginActivity.this);
            finish();
        }, throwable -> {
            //登陆失败
            Log.d(TAG, "accept: "+throwable.getMessage());
            if (throwable instanceof ServerException) {
                Toast.makeText(
                        LoginActivity.this,
                        throwable.getMessage(),
                        Toast.LENGTH_SHORT
                ).show();
            }
        }).dispose());

        //加载验证码图片
        viewModel.loadVerificationCodeImage(new RQDeviceCode(FR.deviceCodeContent));
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    //验证码图片点击监听
    @OnClick(R2.id.verification_code_image)
    void verificationCodeImageOnClick() {
        viewModel.loadVerificationCodeImage(new RQDeviceCode(FR.deviceCodeContent));
    }

    //登陆验证
    boolean loginVerification() {
        boolean result = true;
        //数据不合法抖动动画
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        //验证验证码
        String verification = verificationCode.getText().toString();
        if (DataVerification.verificationCodeFormatVerification(verification)) {
            verificationCodeLayout.startAnimation(shake);
            verificationCode.setFocusable(true);
            result = false;
        }
        //密码验证
        String userPassword = this.userPassword.getText().toString();
        if (!DataVerification.userPasswordFormatVerification(userPassword)
                || !DataVerification.userPasswordLengthVerification(userPassword)) {
            userPasswordLayout.startAnimation(shake);
            this.userPassword.setFocusable(true);
            result = false;
        }
        //账号验证
        String userAccount = this.userAccount.getText().toString();
        if (!DataVerification.userAccountFormatVerification(userAccount)
                || !DataVerification.userAccountLengthVerification(userAccount)) {
            userAccountLayout.startAnimation(shake);
            this.userAccount.setFocusable(true);
            result = false;
        }
        return result;
    }
}
